from server import db, Redis
import os
from os import getenv, path
import requests
from dotenv import load_dotenv
from flask import Flask, request, jsonify

# 加载 .env 文件中的环境变量
load_dotenv()
# 从环境变量中获取 APPID 和 APPSECRET
APPID = getenv('G_APPID')
APPSECRET = getenv('G_SECRET')


def get_access_token():
    access_token = Redis.get('wechat_access_token')
    if access_token:
        return access_token
    else:
        try:
            url = f"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APPID}&secret={APPSECRET}"
            response = requests.get(url)
            data = response.json()
            if 'access_token' in data:
                access_token = data['access_token']
                expires_in = data['expires_in']
                Redis.set('wechat_access_token', access_token, ex=expires_in)
                return access_token
            else:
                print('Error fetching access token:', data)
        except Exception as e:
            print('获取token失败:', str(e))


def get_wechat_users(access_token):
    url = f"https://api.weixin.qq.com/cgi-bin/user/get?access_token={access_token}&next_openid="
    response = requests.get(url)
    data = response.json()
    if 'data' in data and 'openid' in data['data']:
        return data['data']['openid']
    else:
        print('Error fetching user list:', data)
        return []


def get_wechat_user_info(access_token, open_id):
    url = f"https://api.weixin.qq.com/cgi-bin/user/info?access_token={access_token}&openid={open_id}&lang=zh_CN"
    response = requests.get(url)
    data = response.json()
    return data


def send_template_message(to_user, template_id, data, url=None):
    access_token = get_access_token()
    api_url = f"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={access_token}"
    payload = {
        "touser": to_user,
        "template_id": template_id,
        "data": data
    }
    if url:
        payload['url'] = url
    response = requests.post(api_url, json=payload)
    return response.json()


def send_order_notification(admin_users, order_info):
    try:
        template_id = "LoMETh8z1t8axJmKCH9XXLtdXn5jKAMjLh9ZvpCVb9o"  # 模板ID
        access_token = get_access_token()  # 获取 access_token
        user_list = get_wechat_users(access_token)  # 获取公众号用户列表

        for open_id in user_list:
            user_info = get_wechat_user_info(access_token, open_id)
            union_id = user_info.get('unionid')
            # print(union_id)
            # if not union_id:
            #     continue

            # for admin_user in admin_users:
            data = {
                "character_string1": {
                    "value": order_info['id'],
                    "color": "#173177"
                },
                "thing13": {
                    "value": order_info['user_name'],
                    "color": "#173177"
                },
                "phone_number14": {
                    "value": order_info['phone'],
                    "color": "#173177"
                },
                "thing18": {
                    "value": order_info['address'],
                    "color": "#173177"
                }
            }
            # 发送模板消息
            result = send_template_message(open_id, template_id, data)
            # print(f"推送订阅消息给{admin_user.nick_name}")
            print(result)

    except Exception as e:
        print('Error:', str(e))
        return jsonify({'error': str(e)}), 500



# def send_order_notification(admin_users, order_info):
#     try:
#         template_id = "LoMETh8z1t8axJmKCH9XXLtdXn5jKAMjLh9ZvpCVb9o"  # 模板ID
#         user_list = get_wechat_users()
#         print(user_list)
#         for user in admin_users:
#             # 构建模板数据
#             user = user.open_id
#             data = {
#                 "character_string1": {
#                     "value": order_info['id'],
#                     "color": "#173177"
#                 },
#                 "thing13": {
#                     "value": order_info['user_name'],
#                     "color": "#173177"
#                 },
#                 "phone_number14": {
#                     "value": order_info['phone'],
#                     "color": "#173177"
#                 },
#                 "thing18": {
#                     "value": order_info['address'],
#                     "color": "#173177"
#                 }
#             }
#             # 发送模板消息
#             result = send_template_message(user, template_id, data)
#             print(f"推送订阅消息给{user.nick_name}")
#             print(result)
#
#     except Exception as e:
#         print('Error:', str(e))
#         return jsonify({'error': str(e)}), 500
#
#
# def get_wechat_users():
#     access_token = get_access_token()
#     if not access_token:
#         return jsonify({'error': 'Unable to get access token'}), 500
#
#     next_openid = None  # Initialize with None to get the first page
#     user_list = []
#
#     url = f"https://api.weixin.qq.com/cgi-bin/user/get?access_token={access_token}"
#     if next_openid:
#         url += f"&next_openid={next_openid}"
#
#     try:
#         response = requests.get(url)
#         data = response.json()
#
#         if 'errcode' in data:
#             return jsonify({'error': data}), 500
#
#         user_list.extend(data.get('data', {}).get('openid', []))
#         next_openid = data.get('next_openid')
#
#         if not next_openid:
#             return user_list
#         print(user_list)
#     except Exception as e:
#         return jsonify({'error': str(e)}), 500
#     return jsonify({'user_list': user_list})


# 小程序一次性订阅，安卓可接收多次，ios只能一次
def send_subscription_notification(admin_users, order_info):
    """
    向管理员用户发送微信订阅通知
    Args:
        admin_users: 包含管理员用户信息的列表
        order_info: 要推送的工单信息
    """
    template_id = "S4NIsxVKQwnORaYGkVbWf2a7AKeMP0zDZa_IguZqRQg"  # 模板ID
    template_no = "46310"  # 模板编号

    for user in admin_users:
        # 构建订阅消息内容，包括工单编号、客户姓名、详细地址、客户电话等信息
        message_data = {
            "touser": user.open_id,
            "template_id": template_id,
            "data": {
                "character_string1": {"value": order_info["id"]},
                "short_thing2": {"value": order_info["user_name"]},
                "thing8": {"value": order_info["address"]},
                "phone_number13": {"value": order_info["phone"]}
            }

        }
        print("推送订阅消息给%s" % user.nick_name)
        # 调用微信订阅通知推送的 API
        WECHAT_APPID = getenv("WECHAT_APPID")
        WECHAT_SECRET = getenv("WECHAT_SECRET")
        token_url = f"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={WECHAT_APPID}&secret={WECHAT_SECRET}"
        COMPONENT_ACCESS_TOKEN = requests.get(token_url).json()["access_token"]
        url = f"https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={COMPONENT_ACCESS_TOKEN}"
        response = requests.post(url, json=message_data)
        if response.status_code == 200:
            print(f"消息推送成功: {response.json()}")
        else:
            print(f"消息推送失败: {response.text}")